<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" ref="crud" v-model="form" @row-del="rowDel" @row-update="rowUpdate" @row-save="rowSave" :before-open="beforeOpen" @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange" @refresh-change="refreshChange" @on-load="onLoad" :span-method="spanMethod">
      <template slot="menuRight">
        <table-right :crud='$refs.crud' :data='data' :searchBtn="false" :columnBtn="false" :addPermission="!isHavePFMEA" :handleDelete="handleDelete" :delPermission="false" :refreshChange='refreshChange'>
          <!-- <el-button type="text" icon="el-icon-s-promotion" v-if="permission.projectcontrol_pfmea_submit" @click="handleSubmit">提交</el-button> -->
        </table-right>
      </template>
      <template slot-scope="{row}" slot="rpn" v-if="row.frequency&&row.detection&&row.severity">{{row.frequency*row.detection*row.severity}}</template>
      <template slot-scope="{row}" slot="detectProcessControl">
        <div class="prdList">
          <div class="prdItem" v-for="(item,index) in row.scListItems" :key="index">
            {{item.checkToolName}}/{{item.capacity}}/{{item.frequency}}
          </div>
        </div>
      </template>
      <template slot-scope="{row}" slot="menu">
        <el-tooltip class="item" effect="dark" content="查看" placement="bottom">
          <el-button icon="el-icon-view" size="small" type="text" @click.stop="$refs.crud.rowView(row,row.$index)"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
          <el-button icon="el-icon-edit" size="small" :disabled="row.fmeaStatus != 1" type="text" @click.stop="$refs.crud.rowEdit(row,row.$index)" v-if="isCheck(row.createUser, userId)"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
          <el-button icon="el-icon-delete" size="small" :disabled="row.fmeaStatus != 1" type="text" @click.stop="rowDel(row)" v-if="isCheck(row.createUser, userId)"></el-button>
        </el-tooltip>
        <!-- <el-tooltip content="跟踪" style="height:auto" effect="dark" class="rightbtn" placement="bottom" v-if="row.createUser==userId&&permission.projectcontrol_pfmea_track">
          <div class="top-bar__item">
            <el-button type="text" size="small" :disabled="row.fmeaStatus == 1" icon="el-icon-share" @click.stop="handleImage(row)"></el-button>
          </div>
        </el-tooltip> -->
      </template>
      <template slot="stage" slot-scope="{row}">{{row.stageName}}</template>
      <template slot="infoForm" slot-scope="scope">
        <avue-crud class='scopeCrud' ref="scopeCrud" :table-loading="scopeloading" :page='false' :option="option2" :data="scopeData" v-model="scopeForm">
          <template slot-scope="{row}" slot="rpn" v-if="row.frequency&&row.detection&&row.severity">{{row.frequency*row.detection*row.severity}}</template>
          <template slot-scope="{row}" slot="potentialFailMode">
            <el-select size="mini" v-model="row.potentialFailMode" filterable placeholder="请选择潜在失效模式">
              <el-option v-for="item in row.fmeaModes" :key="item.id" :label="item.mode" :value="item.id">
              </el-option>
            </el-select>
          </template>
          <template slot-scope="{row}" slot="potentialFailResult">
            <el-select size="mini" v-model="row.potentialFailResult" filterable placeholder="请选择潜在失效后果">
              <el-option v-for="item in row.fmeaResults" :key="item.id" :label="item.result" :value="item.id">
              </el-option>
            </el-select>
          </template>
          <template slot-scope="{row}" slot="potentialFailReason">
            <el-select size="mini" v-model="row.potentialFailReason" filterable placeholder="请选择潜在失效原因">
              <el-option v-for="item in row.fmeaReasons" :key="item.id" :label="item.reason" :value="item.id">
              </el-option>
            </el-select>
          </template>
          <template slot-scope="{row}" slot="preventProcessControl">
            <el-select size="mini" v-model="row.preventProcessControl" filterable placeholder="请选择现行预防过程控制">
              <el-option v-for="item in row.fmeaPrevents" :key="item.id" :label="item.prevent" :value="item.id">
              </el-option>
            </el-select>
          </template>
          <template slot-scope="{row}" slot="detectProcessControl">
            <div class="prdList">
              <div class="prdItem" v-for="(item,index) in row.scListItems" :key="index">
                <!-- <span v-if="item.fixtureNo">{{item.fixtureName}}({{item.fixtureNo}})</span> -->
                {{item.checkToolName}}/{{item.capacity}}/{{item.frequency}}
              </div>
            </div>
          </template>
        </avue-crud>
      </template>
    </avue-crud>
    <el-dialog title="流程图" :visible.sync="flowBox" width="80%" append-to-body='true'>
      <img :src="flowUrl" width="100%" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="flowBox = false">关 闭</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>
<script>
import { getNewestFmea, removeFmea, getDetailProduct, updateFmea, submitFmea } from '@/api/projectcontrol/fmea';
import { getAllMembers } from '@/api/projectcontrol/controlplan';
import { masterProducts } from '@/api/project/productData/product';
import { mapGetters } from 'vuex';
import { init } from '@/mixins/init';
import { deepClone } from '@/util/util.js';
import { getBusinessList } from '@/api/zidian';
export default {
  mixins: [init],
  components: {},
  props: {
    productId: {
      type: String,
    },
    materialName: {
      type: String,
    },
    innerDrawingNo: {
      type: String,
    },
    materialNo: {
      type: String,
    },
    type: {
      type: String,
    },
  },
  data() {
    return {
      mode: '', //潜在失效模式
      result: '', //潜在失效后果
      severity: '', //严重程度
      isDetail: 1,
      searchDetail: '',
      flowBox: false,
      flowUrl: '',
      personId: '', //当前用户对应的人员id
      documentList: [], //apqp模板文件list
      stageList: [],
      problemList: [],
      severityList: [], //严重程度
      scopeloading: false,
      isHavePFMEA: false,
      option: {
        size: 'mini',
        page: false,
        dialogWidth: '90%',
        dialogMaxHeight: '720',
        maxHeight: 600,
        tip: false,
        border: true,
        // index: true,
        // indexLabel: '序号',
        selection: true,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        addBtn: false,
        menuWidth: 120,
        columnBtn: true,
        filterBtn: true,
        searchMenuSpan: 12,
        dialogClickModal: false,
        labelWidth: 110,
        defaultExpandAll: true,
        column: [
          {
            label: 'PFMEA编号',
            prop: 'fmeaPlanNo',
            span: 12,
            maxlength: 15,
            width: 100,
            overHidden: true,
            rules: [
              {
                required: true,
                message: '请输入PFMEA编号',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '产品',
            prop: 'productId',
            hide: true,
            showColumn: false,
            disabled: true,
            type: 'select',
            dicData: [],
            props: {
              label: 'label',
              value: 'id',
            },
            rules: [
              {
                required: true,
                message: '请选择产品',
                trigger: 'blur',
              },
            ],
            span: 12,
            minWidth: 130,
            filterable: true,
            change: (val) => {
              if (val.value) {
                if (this.formType == 'add') {
                  this.scopeloading = true;
                  getDetailProduct(val.value).then((res) => {
                    this.scopeloading = false;
                    if (res.data.success) {
                      var list = res.data.data.fmeaDetails;
                      list.map((item) => {
                        item.$cellEdit = true;
                      });
                      this.scopeData = list;
                    }
                  });
                }
              }
            },
          },
          {
            label: '产品阶段',
            prop: 'stage',
            span: 12,
            minWidth: 100,
            slot: true,
            type: 'checkbox',
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=product_stage',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            rules: [
              {
                required: true,
                message: '请选择产品阶段',
                trigger: 'change',
              },
            ],
          },
          {
            label: '产品图号',
            prop: 'innerDrawingNo',
            span: 12,
            hide: true,
            showColumn: false,
            disabled: true,
          },
          {
            label: '产品编号',
            prop: 'materialNo',
            span: 12,
            hide: true,
            showColumn: false,
            disabled: true,
          },
          {
            label: '关键日期',
            prop: 'validDate',
            type: 'date',
            valueFormat: 'yyyy-MM-dd',
            width: 100,
            span: 12,
            // editDisabled: true,
            rules: [
              {
                required: true,
                message: '请选择关键日期',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '核心小组',
            prop: 'coreGroup',
            type: 'select',
            hide: true,
            showColumn: false,
            dicData: [],
            multiple: true,
            // dicUrl: '/api/blade-system/dict-biz/dictionary?code=fmea',
            props: {
              label: 'name',
              value: 'id',
            },
            minWidth: 150,
            rules: [
              {
                required: true,
                message: '请选择核心小组',
                trigger: 'change',
              },
            ],
          },
          { label: '过程责任部门', prop: 'coreGroupDeps', disabled: true, hide: true, showColumn: false },
          {
            label: '编制',
            prop: 'chargeId',
            type: 'select',
            hide: true,
            showColumn: false,
            dicData: [],
            props: {
              label: 'name',
              value: 'id',
            },
            minWidth: 150,
            rules: [
              {
                required: true,
                message: '请选择编制人',
                trigger: 'change',
              },
            ],
          },
          {
            label: '创建日期',
            prop: 'createDate',
            hide: true,
            showColumn: false,
            type: 'date',
            valueFormat: 'yyyy-MM-dd',
            span: 12,
            width: 100,
            rules: [
              {
                required: true,
                message: '请选择创建日期',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '最后修订日期',
            prop: 'finalUpdateDate',
            hide: true,
            showColumn: false,
            type: 'date',
            valueFormat: 'yyyy-MM-dd',
            span: 12,
            width: 100,
          },
          { label: '批准', prop: 'coreGroupDeps', display: false, hide: true, showColumn: false },
          {
            label: '步骤序号',
            prop: 'processNo',
            display: false,
            hide: false,
            maxlength: 5,
            disabled: true,
            rules: [
              {
                required: true,
                message: '请输入步骤序号',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '工序名称',
            prop: 'processName',
            display: false,
            hide: false,
            disabled: true,
            minWidth: 120,
          },
          {
            label: '特殊特性',
            prop: 'productFeature',
            disabled: true,
            hide: false,
            display: false,
          },
          {
            label: '潜在失效模式',
            prop: 'mode',
            display: false,
            minWidth: 150,
            maxlength: 60,
          },
          {
            label: '潜在失效后果',
            prop: 'result',
            display: false,
            minWidth: 150,
            maxlength: 60,
          },
          {
            label: 'S',
            prop: 'severity',
            display: false,
            minWidth: 70,
            type: 'select',
            dicData: [],
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            span: 12,
          },
          {
            label: '分类',
            prop: 'quaTypeName',
            width: 70,
            display: false,
          },
          {
            label: '潜在失效原因/机理',
            prop: 'reason',
            display: false,
            span: 12,
            minWidth: 180,
          },
          {
            label: 'O',
            prop: 'frequency',
            display: false,
            type: 'select',
            dicData: [],
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            span: 12,
          },
          {
            label: '现行预防过程控制',
            prop: 'prevent',
            display: false,
            span: 12,
            minWidth: 180,
          },
          {
            label: '现行探测过程控制',
            prop: 'detectProcessControl',
            display: false,
            slot: true,
            span: 12,
            minWidth: 180,
          },
          {
            label: 'D',
            prop: 'detection',
            display: false,
            type: 'select',
            dicData: [],
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            span: 12,
          },
          { label: 'RPN', prop: 'rpn', display: false, slot: true },
          {
            labelPosition: 'top',
            prop: 'info',
            span: 24,
            formslot: true,
            hide: true,
            showColumn: false,
          },
          {
            label: '状态',
            prop: 'fmeaStatus',
            span: 12,
            width: 60,
            display: false,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=special_status',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
          },
        ],
      },
      data: [],
      memberList: [], //产品下的项目组成员
      goon: false,
      formType: 'add',
      form: {},
      option2: {
        dialogModal: true,
        menu: false,
        selection: false,
        editBtn: true,
        viewBtn: true,
        delBtn: false,
        index: true,
        tip: false,
        header: false,
        page: false,
        maxHeight: 400,
        column: [
          {
            label: '步骤序号',
            prop: 'processNo',
            width: 70,
          },
          {
            label: '工序名称',
            prop: 'processName',
            overHidden: true,
          },
          {
            label: '产品特性',
            prop: 'productFeature',
            overHidden: true,
          },
          {
            label: '潜在失效模式',
            prop: 'potentialFailMode',
            slot: true,
            cell: true,
            minWidth: 180,
          },
          {
            label: '潜在失效后果',
            prop: 'potentialFailResult',
            slot: true,
            cell: true,
            span: 12,
            minWidth: 180,
            maxlength: 60,
          },
          {
            label: 'S',
            prop: 'severity',
            type: 'select',
            dicData: [],
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            cell: true,
            span: 12,
          },
          {
            label: '分类',
            prop: 'quaTypeName',
            width: 70,
          },
          {
            label: '潜在失效原因/机理',
            prop: 'potentialFailReason',
            slot: true,
            cell: true,
            span: 12,
            minWidth: 180,
          },
          {
            label: 'O',
            prop: 'frequency',
            type: 'select',
            dicData: [],
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            cell: true,
            span: 12,
          },
          {
            label: '现行预防过程控制',
            prop: 'preventProcessControl',
            slot: true,
            cell: true,
            span: 12,
            minWidth: 180,
          },
          {
            label: '现行探测过程控制',
            prop: 'detectProcessControl',
            slot: true,
            span: 12,
            minWidth: 180,
          },
          {
            label: 'D',
            prop: 'detection',
            type: 'select',
            dicData: [],
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            cell: true,
            span: 12,
          },
          { label: 'RPN', prop: 'rpn', slot: true },
          {
            label: '推荐措施',
            prop: 'measures',
            cell: true,
            span: 12,
            minWidth: 250,
            maxlength: 60,
          },
        ],
      },
      scopeData: [],
    };
  },
  watch: {
    'form.productId'(val, oldVal) {
      if (val) {
        getAllMembers({ productId: val }).then((res) => {
          const data = res.data.data;
          this.findObject(this.option.column, 'coreGroup').dicData = data;
          this.memberList = data;
        });
      }
    },
    'form.coreGroup'(val, oldVal) {
      if (val && val.length > 0) {
        let deps = new Set();
        let chargers = [];
        val.forEach((m) => {
          this.memberList.every((member) => {
            if (member.id == m) {
              deps.add(member.departmentName);
              chargers.push(member);
              return false;
            } else {
              return true;
            }
          });
        });
        if (this.form.chargeId) {
          let isHave = chargers.some((item) => item.id == this.form.chargeId);
          if (!isHave) {
            this.$set(this.form, 'chargeId', '');
          }
        }
        this.findObject(this.option.column, 'chargeId').dicData = chargers;
        this.$set(this.form, 'coreGroupDeps', [...deps].join(','));
      }
    },
  },
  computed: {
    ...mapGetters(['userId', 'permission']),
  },
  created() {
    if (this.type == 'edit') {
      this.option.header = true;
      this.option.menu = true;
    } else {
      this.option.header = false;
      this.option.menu = false;
    }
    this.findObject(this.option.column, 'productId').dicData = [
      { label: this.materialName + '（' + this.innerDrawingNo + '）', id: this.productId },
    ];
    getBusinessList('product_stage').then((res) => {
      this.stageList = res.data.data;
    });
    getBusinessList('pasi').then((res) => {
      this.findObject(this.option.column, 'severity').dicData = res.data.data;
      this.findObject(this.option.column, 'frequency').dicData = res.data.data;
      this.findObject(this.option.column, 'detection').dicData = res.data.data;
      this.findObject(this.option2.column, 'severity').dicData = res.data.data;
      this.findObject(this.option2.column, 'frequency').dicData = res.data.data;
      this.findObject(this.option2.column, 'detection').dicData = res.data.data;
      this.severityList = res.data.data;
    });
    this.onLoad();
  },
  methods: {
    spanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.searchDetail == 1) {
        if (
          columnIndex === 0 ||
          columnIndex === 1 ||
          columnIndex === 2 ||
          columnIndex === 3 ||
          columnIndex === 11 ||
          columnIndex === 12 ||
          columnIndex === 13 ||
          columnIndex === 14 ||
          columnIndex === 15 ||
          columnIndex === 17
        ) {
          if (row.itemSpan) {
            return {
              rowspan: row.itemSpan,
              colspan: 1,
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0,
            };
          }
        }
      } else {
        if (
          columnIndex === 0 ||
          columnIndex === 1 ||
          columnIndex === 2 ||
          columnIndex === 3 ||
          columnIndex === 4 ||
          columnIndex === 6
        ) {
          if (row.itemSpan) {
            return {
              rowspan: row.itemSpan,
              colspan: 1,
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0,
            };
          }
        }
      }
    },
    addSpanNumber() {
      const KEY_NAME = 'fmeaPlanNo';
      const KEY_ROWSPAN = 'itemSpan';
      var k = 0;
      while (k < this.data.length) {
        this.data[k][KEY_ROWSPAN] = 1;
        for (var i = k + 1; i <= this.data.length - 1; i++) {
          if (this.data[k][KEY_NAME] === this.data[i][KEY_NAME] && this.data[k][KEY_NAME] !== '') {
            this.data[k][KEY_ROWSPAN]++;
          } else {
            break;
          }
        }
        k = i;
      }
    },
    rowSave(row, done, loading) {
      if (row.id == -1) {
        row.id = '';
        row.status = '';
      }
      row.stage = row.stage.join(',');
      row.coreGroup = row.coreGroup.join(',');
      row.fmeaDetails = this.scopeData;
      updateFmea(row).then(
        () => {
          this.onLoad();
          done();
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        },
        (error) => {
          this.goon = false;
          loading();
        }
      );
    },
    beforeOpen(done, type) {
      this.scopeData = [];
      if (['edit', 'view'].includes(type)) {
        this.formType = type;
        this.$set(this.form, 'innerDrawingNo', this.innerDrawingNo);
        this.$set(this.form, 'materialNo', this.materialNo);
        getDetailProduct(this.form.productId, this.form.fmeaId).then((res) => {
          var list = res.data.data.fmeaDetails;
          if (type == 'edit') {
            list.map((item) => {
              item.$cellEdit = true;
            });
          }
          this.scopeData = list;
          this.form.stage = res.data.data.stage.split(',');
          this.form.coreGroup = res.data.data.coreGroup.split(',');
          this.form.coreGroupName = res.data.data.coreGroupName.split(',');
          this.findObject(this.option.column, 'chargeId').dicData = this.form.coreGroup.map((item, index) => {
            return {
              name: this.form.coreGroupName[index],
              id: item,
            };
          });
          this.form.chargeId = res.data.data.chargeId;
          this.form.id = res.data.data.id;
          this.form.createDate = res.data.data.createDate;
        });
      } else {
        this.$set(this.form, 'productId', this.productId);
        this.$set(this.form, 'innerDrawingNo', this.innerDrawingNo);
        this.$set(this.form, 'materialNo', this.materialNo);
      }
      done();
    },
    rowUpdate(row, index, done, loading) {
      row.stage = row.stage.join(',');
      row.coreGroup = row.coreGroup.join(',');
      delete row.coreGroupName;
      row.fmeaDetails = this.scopeData;
      updateFmea(row).then(
        () => {
          this.onLoad();
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        if (row.id) {
          removeFmea(row.fmeaId).then((req) => {
            if (req.data.success) {
              this.onLoad();
              this.$message.success('操作成功');
            }
          });
        }
      });
    },
    onLoad(page, params = {}) {
      this.loading = true;
      this.query.productId = this.productId;
      getNewestFmea(Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.data = data;
        if (data.length == 0) {
          this.isHavePFMEA = false;
        } else {
          this.isHavePFMEA = true;
        }
        this.loading = false;
        this.addSpanNumber();
        this.selectionClear();
      });
    },
  },
};
</script>
<style lang="scss">
.prdList {
  display: flex;
  flex-direction: column;
}
.prdItem {
  height: 23px;
  overflow: hidden;
  border-bottom: 1px solid #dce4f0;
  &:last-child {
    border-bottom: none;
  }
}
</style>